﻿using AutoMapper;
using MediatR;
using Medical.Api.Read.Application.Command.PackagingSterilization;
using Medical.Api.Read.Dto.PackagingSterilization;
using Medical.Domain.DepartmentInfo;
using Medical.Domain.PackagingSterilization;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using System;

namespace Medical.Api.Read.Application.Handler.PackagingSterilization
{
    /// <summary>
    /// 获取包装登记列表
    /// </summary>
    public class GetPackagingSterilizationHandler : IRequestHandler<GetPackagingSterilizationCommand, ApiResult<List<PackagingSterilizationDTo>>>
    {
        private readonly IBaseRepository<PackagingRegistration> _packRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetPackagingSterilizationHandler> _logger;
        private readonly IBaseRepository<ItemTable> itemRepository;

        public GetPackagingSterilizationHandler(IBaseRepository<PackagingRegistration> packRepository, IMapper mapper, ILogger<GetPackagingSterilizationHandler> logger, IBaseRepository<ItemTable> itemRepository)
        {
            _packRepository = packRepository;
            _mapper = mapper;
            _logger = logger;
            this.itemRepository = itemRepository;
        }

        public Task<ApiResult<List<PackagingSterilizationDTo>>> Handle(GetPackagingSterilizationCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<PackagingSterilizationDTo>> res = new ApiResult<List<PackagingSterilizationDTo>>();

            try
            {
                var query = _packRepository.GetAll().Where(x => !x.IsDeleted);
                var itemtablequery = itemRepository.GetAll().Where(x => !x.IsDeleted);

                // 时间过滤 - 使用PackingTime字段进行过滤
                if (request.StartTime.HasValue && request.EndTime.HasValue)
                {
                    var startDate = request.StartTime.Value.Date;
                    var endDate = request.EndTime.Value.Date.AddDays(1).AddTicks(-1); // 包含结束日期的23:59:59.999
                    query = query.Where(x => x.PackingTime >= startDate && x.PackingTime <= endDate);
                }
                else if (request.StartTime.HasValue)
                {
                    var startDate = request.StartTime.Value.Date;
                    query = query.Where(x => x.PackingTime >= startDate);
                }
                else if (request.EndTime.HasValue)
                {
                    var endDate = request.EndTime.Value.Date.AddDays(1).AddTicks(-1);
                    query = query.Where(x => x.PackingTime <= endDate);
                }

                var linq = from a in itemtablequery
                           join b in query on a.Id equals b.EquipmentPackageId
                           select new PackagingSterilizationDTo
                           {
                               Id = b.Id,
                               ItemName = a.ItemName,
                               ItemCode = a.ItemCode,
                               PackingTime = b.PackingTime,
                               Packer = b.Packer,
                               Examiner = b.Examiner,
                               EquipmentPackageId = b.EquipmentPackageId,
                               Itemattribute = a.Itemattribute,
                               ItemNumber = a.ItemNumber,
                               ItemType = a.ItemType,
                           };

                res.Data = linq.ToList();
                res.Msg = "获取包装登记列表成功";
                res.Code = ApiEnums.Success;
                _logger.LogInformation("获取包装登记列表成功，共{Count}条记录", res.Data.Count);
            }
            catch (Exception ex)
            {
                res.Data = new List<PackagingSterilizationDTo>();
                res.Msg = $"获取包装登记列表失败：{ex.Message}";
                res.Code = ApiEnums.Error;
                _logger.LogError(ex, "获取包装登记列表时发生错误");
            }

            return Task.FromResult(res);
        }
    }
}
